package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Returns the hour for time. The range of the return value is 0 to 23 for
 * time-of-day columnValueList. However, the range of TIME columnValueList
 * actually is much larger, so HOUR can return columnValueList greater than 23.
 *
 * <pre>
 * mysql> SELECT HOUR('10:05:03');
 *         -> 10
 * mysql> SELECT HOUR('272:59:59');
 *         -> 272
 * </pre>
 *
 * @author jianghang 2014-4-16 下午6:16:05
 * @since 5.0.7
 */
public class Hour extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Time time = Type.TimeType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);

        return cal.get(Calendar.HOUR_OF_DAY);
    }

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"HOUR"};
    }
}
